#!/usr/bin/python3
# -*- coding: UTF-8 -*-





from auto_report.auto_report import AutoReport
from openpyxl import load_workbook
import os
import shutil
from auto_report.utils import info, get_font, warning_decrese
from openpyxl.utils.cell import coordinate_from_string
from rich import print


PROJECT_AREA = {
    '2020年抚仙湖生态环境保护与治理项目': '澄江市',
    '2020年通海县杞麓湖生态治理项目': '通海县',
}

TEXT_RED_12 = get_font('ff0000', 12)
TEXT_BLACK_12 = get_font('000000', 12)

EXCEPT_COLS = [11, 13, 15]


DATA_AREA = 'A6:U7'

PRIMARY_COL = 4
DATA_ROW_START = 5
DATA_COL_END = 19

MOD_COL_START = 6
MOD_COL_END = 18

class ZhuanZhaiReport(AutoReport):
    """docstring for LakeReport"""

    def __init__(self, target_month):
        super(ZhuanZhaiReport, self).__init__(target_month)
        self.target_month = target_month
        self.report_name = '地区处-云南省2020年地方政府专项债券（流域水环境治理）项目发行安排情况表'

    def get_src_file(self):
        return f'玉溪市-{self.get_last_month_field()}-{self.report_name}.xlsx'

    def get_dst_file(self):
        return f'玉溪市-{self.get_month_field()}-{self.report_name}.xlsx'

    def __parse_xlsx(self, file_path, min_row=0, max_col=0):
        """
        读取xlsx文件的数据，返回cell对象数组
        """
        wb = load_workbook(file_path, data_only=True)
        ws = wb.active
        data = list(ws.values)[min_row:]
        res = []
        for row in data:
            sub_row = row if max_col == 0 else row[:max_col]
            res.append(sub_row)
        return res

    def __get_source(self):
        """
        获取所有数据源成一个大数组
        """
        source_data = []
        src_folder = f'zhuanzhai/{self.target_month}'
        files = self.get_files(src_folder)
        for f in files:
            data = self.__parse_xlsx(
                f'{src_folder}/{f}', DATA_ROW_START, DATA_COL_END)
            for row in data:
                source_data.append(row)

        return source_data

    def generate(self):
        """
        读取县区报表形成总表
        """
        print('汇总操作')

        src_file = self.get_src_file() if os.path.exists(
            self.get_src_file()) else f'{self.report_name}.xlsx'

        wb = load_workbook(src_file)
        ws = wb.active

        data_source = self.__get_source()

        for row_index, row in enumerate(ws[DATA_AREA]):
            project_name = row[PRIMARY_COL].value
            print('\n')
            print(row_index, '处理', project_name, '数据')
            data_row = [
                r for r in data_source if r[PRIMARY_COL] == project_name]
            if len(data_row) != 1:
                print(f'{project_name} 的数据有误')
                continue
            for col_index in range(MOD_COL_START, MOD_COL_END):
                if col_index in EXCEPT_COLS:
                    print('except', col_index)
                    continue
                new_val = data_row[0][col_index]
                old_val = row[col_index].value
                if old_val != new_val:
                    warning_decrese(
                        row[col_index].coordinate, old_val, new_val)

                    info(
                        f'修改 [bold yellow]{row[col_index].coordinate}[/bold yellow], {row[col_index].value} -> {new_val}')
                    row[col_index].value = new_val
                    row[col_index].font = TEXT_RED_12
                else:
                    row[col_index].font = TEXT_BLACK_12

        ws['A1'].value = f'{self.report_name}{self.get_month_field()}'

        dst_file = self.get_dst_file()

        wb.save(dst_file)

        print('完成')
    
    def split(self):
        """
        按县区拆分
        """
        info('拆分操作')

        src_file = self.get_src_file() if os.path.exists(
            self.get_src_file()) else f'{self.report_name}.xlsx'

        wb = load_workbook(src_file, data_only=True)

        areas = set(PROJECT_AREA.values())

        target_dir = 'dst'
        if os.path.exists(target_dir):
            shutil.rmtree(target_dir)
        os.mkdir(target_dir)

        for index, area in enumerate(areas):
            one_area_file = f'dst/{index}-{area}-{self.get_last_month_field()}-{self.report_name}.xlsx'
            wb.save(one_area_file)
            tmp_wb = load_workbook(one_area_file)
            tmp_ws = tmp_wb.active
            to_delete_row = []
            project_count = 0

            for _, row in enumerate(tmp_ws[DATA_AREA]):
                project_name = row[PRIMARY_COL].value
                row_area = PROJECT_AREA.get(project_name)

                for col_index in range(MOD_COL_START, MOD_COL_END):
                    row[col_index].font = TEXT_BLACK_12

                if area != row_area:
                    abs_row = coordinate_from_string(
                        row[PRIMARY_COL].coordinate)[1]
                    to_delete_row.insert(0, abs_row)
                else:
                    project_count += 1

            print('jige', to_delete_row, project_count)
            for r in to_delete_row:
                tmp_ws.delete_rows(r, 1)
            
            tmp_wb.save(one_area_file)
            
            tmp_wb = load_workbook(one_area_file)
            tmp_ws = tmp_wb.active
            
            for r in range(DATA_ROW_START + project_count + 1, 12):
                tmp_ws.row_dimensions[r].height = 13.5

            tmp_wb.save(one_area_file)

            print('拆分', area, one_area_file)

        print('完成')